/**
 * Created by wust on 2020-03-30 09:17:58
 * Copyright © 2020 wust. All rights reserved.
 */
package com.sc.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.sc.common.cache.CacheAbstract;
import com.sc.common.cache.CacheFactory;
import com.sc.common.enums.RabbitMqOperationTypeEnum;
import com.sc.common.util.CommonUtil;
import com.sc.common.util.MyStringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: wust
 * @date: Created in 2020-03-30 09:17:58
 * @description: 缓存管理消费队列，需要更新缓存时可通过该队列实现
 *
 */
@Component
public class Consumer4CacheQueue {
    static Logger logger = LogManager.getLogger(Consumer4CacheQueue.class);

    @Autowired
    private CacheFactory cacheFactory;


    @RabbitListener(
        containerFactory = "singleListenerContainer",
        bindings = @QueueBinding(
                value = @Queue(
                        value = "${spring.rabbitmq.cache.queue.name}",
                        durable = "${spring.rabbitmq.cache.queue.durable}"
                ),
                exchange = @Exchange(
                        value = "${spring.rabbitmq.cache.exchange.name}",
                        durable = "${spring.rabbitmq.cache.exchange.durable}",
                        type = "${spring.rabbitmq.cache.exchange.type}",
                        ignoreDeclarationExceptions = "${spring.rabbitmq.cache.exchange.ignoreDeclarationExceptions}"
                ),
                key = "${spring.rabbitmq.cache.routing-key}"
        )
    )
    @RabbitHandler
    public void process(final JSONObject jsonObject) {
        logger.info("缓存管理费队列,{}", jsonObject);

        if (!jsonObject.containsKey("spring.application.name")) {
            logger.error("非法的数据格式，必须要包含[spring.application.name]参数");
            return;
        }

        if(!jsonObject.containsKey("opt")){
            logger.error("非法的数据格式，必须要包含[opt]参数");
            return;
        }

        if(!jsonObject.containsKey("category")){
            logger.error("非法的数据格式，必须要包含[category]参数");
            return;
        }

        String opt = jsonObject.getString("opt");
        if(MyStringUtils.isBlank(MyStringUtils.null2String(opt))){
            logger.error("非法的数据格式，必须要包含[opt]参数值");
            return;
        }

        PropertiesPropertySource propertiesPropertySource4applicationProperties = CommonUtil.getPropertiesPropertySource("applicationProperties");
        if(propertiesPropertySource4applicationProperties == null){
            return;
        }

        String applicationNameFromQueue = jsonObject.getString("spring.application.name");

        String source = jsonObject.getString("category");

        Object data = jsonObject.get("data");

        if(MyStringUtils.isBlank(MyStringUtils.null2String(applicationNameFromQueue))){
            // 没有指定应用服务名的消息，忽略
            return;
        }

        String applicationNameFromServer = propertiesPropertySource4applicationProperties.getProperty("spring.application.name").toString();
        if(!applicationNameFromQueue.equals(applicationNameFromServer)){
            // 不属于当前应用触发的缓存更新，则忽略
            return;
        }

        CacheAbstract cacheAbstract = cacheFactory.getCacheBo(source);
        if(cacheAbstract == null){
            return;
        }

        if (opt.equals(RabbitMqOperationTypeEnum.OPR_RESET_CACHE.name())) {
            cacheAbstract.reset();
        } else if (opt.equals(RabbitMqOperationTypeEnum.OPR_ADD.name())) {
            if (data == null) {
                logger.error("非法的数据格式，必须要包含[data]参数");
                return;
            }
            cacheAbstract.add(data);
        } else if (opt.equals(RabbitMqOperationTypeEnum.OPR_BATCH_ADD.name())) {
            if (data == null) {
                logger.error("非法的数据格式，必须要包含[data]参数");
                return;
            }
            List list = (List) data;
            cacheAbstract.batchAdd(list);
        } else if (opt.equals(RabbitMqOperationTypeEnum.OPR_UPDATE.name())) {
            if (data == null) {
                logger.error("非法的数据格式，必须要包含[data]参数");
                return;
            }
            cacheAbstract.updateByPrimaryKey(data);
        } else if (opt.equals(RabbitMqOperationTypeEnum.OPR_BATCH_UPDATE.name())) {
            if (data == null) {
                logger.error("非法的数据格式，必须要包含[data]参数");
                return;
            }
            List list = (List) data;
            cacheAbstract.batchUpdate(list);
        } else if (opt.equals(RabbitMqOperationTypeEnum.OPR_DEL.name())) {
            if (data == null) {
                logger.error("非法的数据格式，必须要包含[data]参数");
                return;
            }
            cacheAbstract.deleteByPrimaryKey(data);
        } else if (opt.equals(RabbitMqOperationTypeEnum.OPR_BATCH_DEL.name())) {
            if (data == null) {
                logger.error("非法的数据格式，必须要包含[data]参数");
                return;
            }
            List list = (List) data;
            cacheAbstract.batchDelete(list);
        }
    }
}
